package com.demo.producer.mqtt;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * 获取配置参数
 */
@Configuration
@IntegrationComponentScan
public class MqttConfig {
    @Value("${mqtt.brokerURL}")
    private String url;
    @Value("${mqtt.clientId}")
    private String clientId;
    @Value("${mqtt.userName}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.connectionTimeout}")
    private Integer timeout;
    @Value("${mqtt.keepAliveInterval}")
    private Integer keepalive;

    /**
     * 设置mqtt的连接工厂
     *
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        String[] array = this.url.split(",");
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(array);
        options.setUserName(this.username);
        options.setPassword(this.password.toCharArray());
        options.setConnectionTimeout(this.timeout);
        options.setKeepAliveInterval(this.keepalive);
        options.setCleanSession(false);
        options.setAutomaticReconnect(true);
        options.setMaxInflight(1000);

        factory.setConnectionOptions(options);
        return factory;
    }

    /**
     * 设置出站通道
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 出站设置
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        // 发送消息和消费消息的channel可以使用相同的MqttPahoClientFactory
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(this.clientId + "_outbound", mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultQos(1);
        // 设置Paho 消息转换器
        DefaultPahoMessageConverter defaultPahoMessageConverter = new DefaultPahoMessageConverter();
        // 如果是字节消息的话，需要设置这个
//        defaultPahoMessageConverter.setPayloadAsBytes(true);
        messageHandler.setConverter(defaultPahoMessageConverter);
        return messageHandler;
    }
}
